package com.jstyle.beatecg.ble;


import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.text.TextUtils;
import com.jstyle.beatecg.app.MyApplication;
import com.jstyle.beatecg.model.MyBluetoothDevice;
import com.jstyle.beatecg.util.SharePreferenceUtils;


/**
 * Created by Administrator on 2017/4/11.
 */

public class BleManager {
    private static BleManager ourInstance;
    public static  BluetoothAdapter bluetoothAdapter;
    static BluetoothManager bluetoothManager;
    Context context;
    private BleManager(Context context) {
        this.context = context;
        bluetoothManager= (BluetoothManager)context.getSystemService(Context.BLUETOOTH_SERVICE);
        bluetoothAdapter=bluetoothManager.getAdapter();
    }

    public static void init(Context context){
        if (ourInstance == null) {
            synchronized (BleManager.class) {
                if (ourInstance == null) {
                    ourInstance = new BleManager(context);
                }
            }
        }
        MyBluetoothDevice address= SharePreferenceUtils.getUser(MyApplication.context,SharePreferenceUtils.KEY_ADDRESS);
        if(null!=address){
            if(address.getIsbind()){
                BleManager.getInstance().connectDevice(address.getDeviceAddress());
            }

        }
    }
    public  static BluetoothAdapter bluetoothAdapter(){ return bluetoothManager.getAdapter(); }
    public  boolean isBleEnable(){
        return bluetoothAdapter().enable();
    }
    public static BleManager getInstance() {
        return ourInstance;
    }
    public void connectDevice(String address){
        if(!bluetoothAdapter().isEnabled()){
            bluetoothAdapter().enable();//如果当前蓝牙开关没有开启话直接打开好了
        }
        if(!bluetoothAdapter().isEnabled()|| TextUtils.isEmpty(address)||isConnected())return;
        BleService.getInstance().initBluetoothDevice(address);

    }




    public void writeValue(byte[]value){
        if(ourInstance==null||!isConnected())return;
        BleService.getInstance().writeValue(value);
    }

    public void offerValue(byte[]data){
        BleService.getInstance().offerValue(data);
    }

    public void writeValue(){
        BleService.getInstance().nextQueue();
    }
    public void disconnectDevice(){
        BleService.getInstance().disconnect();
    }

    public boolean isConnected(){
        return  BleService.getInstance().isConnected();
    }

    public void DisConnecte(){
        BleService.getInstance().disconnect();
    }
}

